package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.swing.text.ChangedCharSetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lo
 * @date 2021/9/21
 */
@Component
@Slf4j
@Order(0)
public class AuthorizeFilter implements GlobalFilter {

    private static List<String> urlList = new ArrayList<>();

    // 初始化白名单 url路径
    static {
        //登录路径
        urlList.add("/login/in");
        //光网关小刀文档路径
        urlList.add("/v2/api-docs");
    }

    /**
     * @param exchange 封装了request 以及 response 对象
     * @param chain    过滤器链(就是放行)
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.获取请求路径
        String path = request.getURI().getPath();
        //3.判断请求路径是否需要拦截
        for (String s : urlList) {
            if (path.contains(s)) {
                //放行
                return chain.filter(exchange);
            }
        }
        //4. 获取请求中携带的token
        String token = request.getHeaders().getFirst("token");
        //校验token
        if (Strings.isBlank(token)) {
            //终止请求并设置401状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //5解析 token
            // 获取载荷信息
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);

            //查看是否过期
            int i = AppJwtUtil.verifyToken(claimsBody);
            // -1：有效，0：有效，1：过期，2：过期
            if (i < 1) {
                Object id = claimsBody.get("id");
                //改变request本身的值
                request.mutate().header("userId",String.valueOf(id));
                //改变exchange本身的值
                exchange.mutate().request(request);
                log.debug("token解析 成功 当前登录用户的id为: {}",id);
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("网关解析token失败  异常原因: {}",e.getMessage());
        }
        //终止请求
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();

    }
}
